<script setup lang="ts">
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import { computed, onMounted, reactive, ref } from "vue";
import dayjs from "dayjs";
import { getGroupList, getStoreList } from "@/api/teaInfuser/store";
import { handleTree } from "@/utils/tree";
import { deviceGetList } from "@/api/teaInfuser/device";
import { isArray, isString, useDark, useECharts } from "@pureadmin/utils";
import {
  deviceCountCharts,
  formulaHomeAmount,
  getChart,
  getChartsList,
  getTopCharts,
  teaFormulaStats
} from "@/api/home";
import { cloneDeep } from "lodash-unified";
import { ObjectProps, PropDefines } from "@/components/AuTable/type";
import { storeGroupSelect } from "@/utils/formSelect";
import { LINE_COLOR, TEXT_COLOR, THEME_COLOR } from "@/utils/constants";
import * as echarts from "echarts"; // 引入echarts, * as echarts 表示引入所有的方法
import ExcelJS from "exceljs"; // 引入exceljs, 用于生成excel文件
import { saveAs } from "file-saver";
import {
  ALARM_TITLE,
  DATA_SUMMARY_TITLE,
  gridOptionBase,
  LETTER_LIST,
  MATERIAL_TITLE,
  TREND_TITLE
} from "@/views/teaInfuser/dashboard/analysis/constant"; // 引入file-saver, 用于保存文件

import { useI18n } from "vue-i18n";
import { pickerOptions } from "@/views/teaInfuser/dashboard/analysis/components/tools";

const { t } = useI18n();
defineOptions({
  name: "DataAnalysis"
});

const props = defineProps<{
  active: number;
}>();

function isNumber(value) {
  return typeof value === "number" && isFinite(value);
}

// region 命名变量集合
const { isDark } = useDark();
const theme = computed(() => (isDark.value ? "dark" : "light"));

const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showExportBtn: false,
  columns: [
    { field: "store_name", title: "tea_infuser.dashboard.store_name" },
    { field: "make_start_time", title: "tea_infuser.dashboard.start_time" },
    {
      field: "make_end_time",
      title: "tea_infuser.dashboard.end_time"
    },
    { field: "formula_name", title: "tea_infuser.dashboard.formula" },
    {
      field: "status_info",
      title: "tea_infuser.dashboard.abnormal_reason"
      // formatter: ({ cellValue }) => {
      //   const makeDetail = JSON.parse(cellValue);
      //   const timeDetail = makeDetail.time_detail
      //     ? JSON.parse(makeDetail.time_detail)
      //     : [];
      //   const overTimeArr = [];
      //   if (!isArray(timeDetail) || !timeDetail.length) {
      //     return "检测到泡茶桶被人为移动";
      //   }
      //   timeDetail.forEach(item => {
      //     overTimeArr.push(parseInt(item.overTime));
      //   });
      //   console.log(isNumber(NaN), isNumber(Infinity));
      //   const overTime = Math.max(...overTimeArr);
      //   if (!isNumber(overTime) || overTime < 60) {
      //     return "检测到泡茶桶被人为移动";
      //   }
      //   return "浸泡超时" + Math.max(...overTimeArr) + "秒";
      // }
    }
    // {
    //   field: "status",
    //   title: "状态",
    //   slots: {
    //     default: "status_default"
    //   }
    // }
  ],
  actions: [],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        return new Promise(async resolve => {
          const res = await getChartsList(params);
          const data = res?.data ?? [];
          const filter = data.filter(v => v.status != 1);
          resolve({
            data: filter,
            pageCount: filter.length
          });
        });
      },
      param: () => {
        return {
          ...getSearchData()
        };
      }
    }
  }
});

const gridOptionMake = reactive<PropDefines>({
  ...cloneDeep(gridOptionBase),
  columns: [
    { field: "index", title: "tea_infuser.dashboard.index", width: 90 },
    {
      field: "formula_name",
      title: "tea_infuser.dashboard.formula_name",
      width: 360
    },
    { field: "attr", title: "tea_infuser.dashboard.attr", width: 190 },
    { field: "num", title: "tea_infuser.dashboard.num" },
    { field: "count", title: "tea_infuser.dashboard.count" },
    { field: "total_num", title: "tea_infuser.dashboard.total_num" },
    { field: "total_count", title: "tea_infuser.dashboard.total_count" }
  ]
});

const gridOptionDetail = reactive<PropDefines>({
  ...cloneDeep(gridOptionBase),
  columns: [
    { field: "index", title: "tea_infuser.dashboard.index", width: 90 },
    {
      field: "formula_name",
      title: "tea_infuser.dashboard.formula_name",
      width: 360
    },
    { field: "attr", title: "tea_infuser.dashboard.attr", width: 190 },
    { field: "num", title: "tea_infuser.dashboard.num" },
    { field: "tea_count", title: "tea_infuser.dashboard.tea_count" },
    { field: "total_tea_count", title: "tea_infuser.dashboard.total_tea_count" }
  ]
});

const makeLoading = ref(false);
const detailLoading = ref(false);

const formRef = ref();
const formList = ref([
  {
    type: "el-date-picker",
    key: "scsj",
    inType: "datetimerange",
    label: "tea_infuser.dashboard.production_time",
    span: 12,
    rangeSeparator: "至",
    startPlaceholder: "tea_infuser.dashboard.start_time",
    endPlaceholder: "tea_infuser.dashboard.end_time",
    valueFormat: "YYYY-MM-DD HH:mm:ss",
    ...pickerOptions(formRef),
    defaultValue: [
      dayjs().subtract(10, "day").format("YYYY-MM-DD HH:mm:ss"),
      dayjs().format("YYYY-MM-DD HH:mm:ss")
    ]
  },
  () => storeGroupSelect("group_idlist", {}, true),
  {
    type: "select",
    key: "store_id",
    label: "tea_infuser.dashboard.store_name",
    placeholder: "tea_infuser.dashboard.store_name_placeholder",
    valueKey: "id",
    labelKey: "name",
    filterable: true,
    options: []
  },
  {
    type: "select",
    key: "device_id",
    label: "tea_infuser.dashboard.device_code",
    placeholder: "tea_infuser.dashboard.device_code_placeholder",
    valueKey: "device_id",
    labelKey: "device_id",
    filterable: true,
    options: [],
    popperClass: "device-popper"
  },
  {
    type: "select",
    key: "status",
    label: "tea_infuser.dashboard.status",
    placeholder: "tea_infuser.dashboard.status_placeholder",
    valueKey: "value",
    labelKey: "label",
    emptyValues: [null, undefined],
    options: [
      {
        value: "",
        label: "tea_infuser.dashboard.status_all"
      },
      {
        value: "1",
        label: "tea_infuser.dashboard.status_normal"
      },
      {
        value: "2",
        label: "tea_infuser.dashboard.status_abnormal"
      }
    ],
    defaultValue: ""
  }
]);
const groupOptions = ref([]);
const radio = ref("1");

const chartLoading = ref(false);

const tableMakeRef = ref();
const tableMtRef = ref();
const tableAlarmRef = ref();
const lineChartRef = ref();
const barChartRef = ref();
const barDevChartRef = ref();
const pieChartRef = ref();

const { setOptions: setLineOptions } = useECharts(lineChartRef, {
  theme
});
const { setOptions: setBarOptions } = useECharts(barChartRef, {
  theme
});
const { setOptions: setBarDevOptions } = useECharts(barDevChartRef, {
  theme
});
// endregion

// region 公共事件集合
const getList = () => {
  getGroupList({
    start_page: 1,
    size: 0,
    hiddenDeviceType: true
  }).then(res => {
    groupOptions.value = handleTree(res.data, "id", "parent_id");
    formRef.value.setFormProps("group_idlist", {
      data: groupOptions.value
    });
  });

  deviceGetList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("device_id", {
      options: res.data.filter(item => item.device_model.includes("ATT-S"))
    });
  });

  getStoreList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("store_id", {
      options: res.data
    });
  });
};

const getSearchData = () => {
  const param = cloneDeep(formRef.value.getFormData());
  radio.value = param.status;

  const groupObjArr = [];
  if (param.group_idlist != undefined && param.group_idlist.length > 0) {
    for (const item of param.group_idlist) {
      groupObjArr.push({ group_id: item });
    }
    param["group_idlist"] = JSON.stringify(groupObjArr);
  }

  param["create_start_time"] = param.scsj[0];
  param["create_end_time"] = param.scsj[1];
  const statusList = !param.status ? [] : param.status == 1 ? [1] : [2, 3];
  param["status_list"] = JSON.stringify(statusList);
  param.device_type = "泡茶机";
  param.hiddenDeviceType = true;
  delete param["scsj"];
  delete param.status;
  return param;
};

const initLineChart = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  // param["status"] = radio.value;
  const yArr = [];
  const xArr = [];
  chartLoading.value = true;
  try {
    const res = await getChart(param);
    let list = res?.data;
    if (list != null && list.length > 0) {
      list.reverse();

      for (let i = 0; i < list.length; i++) {
        yArr.push(list[i].num);
        xArr.push(list[i].time);
      }
    }
    chartLoading.value = false;
  } catch (e) {
    chartLoading.value = false;
  }

  setLineOptions({
    title: {
      // text: "数据趋势（桶）",
      // textStyle: {
      //   color: TEXT_COLOR,
      //   fontSize: 14
      // }
      show: false
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "6%",
      top: "6%",
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      }
    },
    xAxis: {
      type: "category",
      axisTick: {
        show: false // 通过设置 show 为 false 来隐藏刻度线
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
      // data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    series: [
      {
        data: yArr,
        // data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: "line",
        showSymbol: false,
        areaStyle: {
          color: THEME_COLOR + "20"
        },
        lineStyle: {
          color: THEME_COLOR
        }
      }
    ]
  });
};

const initBarChart = async () => {
  const param = getSearchData();

  const pfArr = [];
  const zlArr = [];
  try {
    const res = await getTopCharts(param);
    const list = res.data;

    if (list != null && list.length > 0) {
      // list.reverse();

      for (let i = 0; i < list.length; i++) {
        zlArr.push(list[i].num);
        pfArr.push(list[i].formula_name);
      }
    }
  } catch (e) {}

  setBarOptions({
    title: {
      text: "配方数量top10",
      textStyle: {
        color: TEXT_COLOR,
        fontSize: 14
      }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {
      show: false
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "22%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      axisTick: {
        show: false // 通过设置 show 为 false 来隐藏刻度线
      },
      data: pfArr
      // data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    series: [
      {
        name: "总量",
        type: "bar",
        data: zlArr,
        // data: [120, 200, 150, 80, 70, 110, 130],
        barWidth: "10px",
        itemStyle: {
          color: THEME_COLOR
        }
        // label: {
        //   show: true,
        //   position: "right",
        //   formatter: function (data) {
        //     return data.value as string;
        //   }
        // }
      }
    ]
  });
};

async function getTeaFormulaStats() {
  const mergeRow = [];
  const mergeFormulaList = [];
  const mergeMtList = [];
  const rowData = [];
  makeLoading.value = true;
  detailLoading.value = true;
  try {
    const param = getSearchData();
    param.start_page = 1;
    param.size = 0;
    param.group_idlist = isString(param.group_idlist)
      ? JSON.parse(param.group_idlist)
      : null;
    param.status_list = isString(param.status_list)
      ? JSON.parse(param.status_list)
      : null;
    const res = await teaFormulaStats(param);
    const list = res.data;
    let attrIndex = 0;

    list.forEach((item, index) => {
      const { attrs, ...row } = item;
      const t_count = attrs.reduce((acc, v) => acc + Number(v.count), 0);
      if (attrs?.length) {
        const total_count = t_count > 0 ? t_count / 1000 : 0;
        rowData.push(
          ...item.attrs.map(v => {
            const count = v.count > 0 ? v.count / 1000 : 0;
            return {
              index: index + 1,
              ...v,
              count,
              ...row,
              total_count
            };
          })
        );
      }
      if (attrs?.length > 1) {
        const mergeKeys = ["total_count", "total_num"];
        const mergeFormulaKeys = ["index", "formula_name"];
        const mergeMtKeys = ["total_tea_count"];
        for (const key of mergeMtKeys) {
          mergeMtList.push({
            row: attrIndex,
            col: gridOptionDetail.columns.findIndex(v => v.field === key),
            rowspan: attrs.length,
            colspan: 1
          });
        }
        for (const key of mergeFormulaKeys) {
          mergeFormulaList.push({
            row: attrIndex,
            col: gridOptionMake.columns.findIndex(v => v.field === key),
            rowspan: attrs.length,
            colspan: 1
          });
        }
        for (const key of mergeKeys) {
          mergeRow.push({
            row: attrIndex,
            col: gridOptionMake.columns.findIndex(v => v.field === key),
            rowspan: attrs.length,
            colspan: 1
          });
        }

        attrIndex += attrs.length;
      } else {
        attrIndex++;
      }
    });

    makeLoading.value = false;
    detailLoading.value = false;
  } catch (e) {
    makeLoading.value = false;
    detailLoading.value = false;
  }

  console.log("mergeRow", mergeRow);
  gridOptionMake.vxeTableConfig.mergeCells = [...mergeFormulaList, ...mergeRow];
  gridOptionMake.dataSource = rowData;

  gridOptionDetail.vxeTableConfig.mergeCells = [
    ...mergeFormulaList,
    ...mergeMtList
  ];
  gridOptionDetail.dataSource = rowData;
}

// endregion

// region 组件事件集合
const onsubmit = () => {
  initLineChart();
  initBarChart();
  getTeaFormulaStats();
  // initDevicePieChart();
  // initDevBarChart();
  tableAlarmRef.value?.refresh();
};

// endregion

onMounted(() => {
  getList();
  onsubmit();
  // initLineChart();
});

const getYcyy = makeDetail => {
  const timeDetail = makeDetail.time_detail
    ? JSON.parse(makeDetail.time_detail)
    : [];
  const overTimeArr = [];
  if (!isArray(timeDetail) || !timeDetail.length) {
    return t("tea_infuser.dashboard.bucket_moved");
  }
  timeDetail.forEach(item => {
    overTimeArr.push(parseInt(item.overTime));
  });

  const overTime = Math.max(...overTimeArr);
  if (!isNumber(overTime) || overTime < 60) {
    return t("tea_infuser.dashboard.bucket_moved");
  }
  return t("tea_infuser.dashboard.soak_timeout", {
    time: Math.max(...overTimeArr)
  });
};

const exportQs = async () => {
  const workbook = new ExcelJS.Workbook(); // 创建工作簿
  const qsWorksheet = workbook.addWorksheet(TREND_TITLE); // 添加工作表
  const param = getSearchData(); //查询参数
  param["grouptime"] = "day";
  //泡茶趋势列表
  const qsRes = await getChart(param);
  const qsList = qsRes.data;
  //time,num
  let qsIndex = 0;
  // qsWorksheet.getCell("A" + qsIndex).value = "泡茶趋势列表";
  const qsTitleRow = qsWorksheet.getRow(qsIndex);
  qsTitleRow.font = { bold: true };
  qsIndex = qsIndex + 1;
  qsWorksheet.insertRow(qsIndex, ["日期", "泡茶数量"]);
  const qsHeadRow = qsWorksheet.getRow(qsIndex);
  const qsHeaderColumns = ["A", "B"];
  qsHeaderColumns.forEach(col => {
    const cell = qsWorksheet.getCell(`${col}` + qsIndex);
    cell.alignment = {
      vertical: "middle",
      horizontal: "center",
      wrapText: true // 允许文本换行
    };
    cell.fill = {
      type: "pattern",
      pattern: "solid",
      fgColor: { argb: "FFCCCCCC" }
    };
  });
  for (const [index, item] of qsList.entries()) {
    const tablebodydata = [item.time, item.num];
    qsIndex = qsIndex + 1;
    qsWorksheet.insertRow(qsIndex, tablebodydata);
    qsWorksheet.getRow(qsIndex).alignment = { horizontal: "center" };
  }

  const qsColumnWidths = {
    A: 20,
    B: 15
  };

  Object.entries(qsColumnWidths).forEach(([col, width]) => {
    qsWorksheet.getColumn(col).width = width;
  });

  workbook.xlsx.writeBuffer().then(function (buffer) {
    // 生成excel文件的二进制数据
    saveAs.saveAs(
      new Blob([buffer], {
        // 生成Blob对象
        type: "application/octet-stream" // 指定文件的MIME类型
      }),
      TREND_TITLE + ".xlsx"
    ); // 指定文件名
  });
};

const exportMake = async (grid: PropDefines, name: string) => {
  const workbook = new ExcelJS.Workbook(); // 创建工作簿
  const worksheet = workbook.addWorksheet(name); // 添加工作表
  //泡茶趋势列表
  const qsList = grid.dataSource;
  //time,num
  let qsIndex = 0;
  const qsTitleRow = worksheet.getRow(qsIndex);
  qsTitleRow.font = { bold: true };
  qsIndex = qsIndex + 1;
  const titles = grid.columns.map(v => v.title);
  worksheet.insertRow(qsIndex, titles);
  // const qsHeadRow = worksheet.getRow(qsIndex);
  // console.log("qsHeadRow", qsHeadRow);
  const qsHeaderColumns = LETTER_LIST.slice(0, grid.columns.length);

  qsHeaderColumns.forEach(col => {
    const cell = worksheet.getCell(`${col}` + qsIndex);
    cell.alignment = {
      vertical: "middle",
      horizontal: "center",
      wrapText: true // 允许文本换行
    };
    cell.fill = {
      type: "pattern",
      pattern: "solid",
      fgColor: { argb: "FFCCCCCC" }
    };
  });
  const keys: string[] = grid.columns.map(v => v.field);
  for (const [index, item] of qsList.entries()) {
    const itemData = keys.map(key => item[key]);
    // const tablebodydata = [item.time, item.num];
    qsIndex = qsIndex + 1;
    worksheet.insertRow(qsIndex, itemData);
    worksheet.getRow(qsIndex).alignment = { horizontal: "center" };
  }
  grid.vxeTableConfig.mergeCells.forEach(item => {
    const cell = `${LETTER_LIST[item.col as number]}${item.row + 2}:${LETTER_LIST[item.col as number]}${[item.row + item.rowspan + 1]}`;
    worksheet.mergeCells(cell);
    worksheet.getCell(
      `${LETTER_LIST[item.col as number]}${item.row + 2}`
    ).alignment = {
      vertical: "middle",
      horizontal: "center",
      wrapText: true // 允许文本换行
    };
  });

  const qsColumnWidths = {
    A: 20,
    B: 15,
    C: 15,
    D: 15,
    E: 15,
    F: 15
  };

  Object.entries(qsColumnWidths).forEach(([col, width]) => {
    worksheet.getColumn(col).width = width;
  });

  workbook.xlsx.writeBuffer().then(function (buffer) {
    // 生成excel文件的二进制数据
    saveAs.saveAs(
      new Blob([buffer], {
        // 生成Blob对象
        type: "application/octet-stream" // 指定文件的MIME类型
      }),
      name + ".xlsx"
    ); // 指定文件名
  });
};

const exportAlarm = async () => {
  const workbook = new ExcelJS.Workbook();
  const ycWorksheet = workbook.addWorksheet(
    t("tea_infuser.dashboard.alarm_title")
  );
  let ycIndex = 0;
  const param = getSearchData();
  const tableRes = await getChartsList(param);

  const titleRow = ycWorksheet.getRow(ycIndex);
  titleRow.font = { bold: true };
  ycIndex = ycIndex + 1;
  ycWorksheet.insertRow(ycIndex, [
    t("tea_infuser.dashboard.serial_number"),
    t("tea_infuser.dashboard.store_name"),
    t("tea_infuser.dashboard.make_start_time"),
    t("tea_infuser.dashboard.make_end_time"),
    t("tea_infuser.dashboard.formula"),
    t("tea_infuser.dashboard.abnormal_reason")
  ]);
  const headRow = ycWorksheet.getRow(ycIndex);
  const headerColumns = ["A", "B", "C", "D", "E", "F"];
  headerColumns.forEach(col => {
    const cell = ycWorksheet.getCell(`${col}` + ycIndex);
    cell.alignment = {
      vertical: "middle",
      horizontal: "center",
      wrapText: true // 允许文本换行
    };
    cell.fill = {
      type: "pattern",
      pattern: "solid",
      fgColor: { argb: "FFCCCCCC" }
    };
  });
  for (const [index, item] of tableRes.data.entries()) {
    // const ycyy = ref();
    // const makeDetail = JSON.parse(item.make_detail);
    // ycyy.value = getYcyy(makeDetail);
    const tablebodydata = [
      index + 1,
      item.store_name,
      item.make_start_time,
      item.make_end_time,
      item.formula_name,
      item.status_info
    ];
    ycIndex = ycIndex + 1;
    ycWorksheet.insertRow(ycIndex, tablebodydata);
    ycWorksheet.getRow(ycIndex).alignment = { horizontal: "center" };
  }

  const columnWidths = {
    A: 10,
    B: 15,
    C: 25,
    D: 25,
    E: 10,
    F: 30
  };

  Object.entries(columnWidths).forEach(([col, width]) => {
    ycWorksheet.getColumn(col).width = width;
  });

  workbook.xlsx.writeBuffer().then(function (buffer) {
    // 生成excel文件的二进制数据
    saveAs.saveAs(
      new Blob([buffer], {
        // 生成Blob对象
        type: "application/octet-stream" // 指定文件的MIME类型
      }),
      t("tea_infuser.dashboard.alarm_title") + ".xlsx"
    ); // 指定文件名
  });
};

const exportExcel = (type: string) => {
  const exports = {
    qs: exportQs,
    make: () => exportMake(gridOptionMake, DATA_SUMMARY_TITLE),
    material: () => exportMake(gridOptionDetail, MATERIAL_TITLE),
    alarm: exportAlarm
  };
  exports[type]?.();
};
</script>

<template>
  <div id="test-id" class="home-wrap h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm
        ref="formRef"
        :formList="formList"
        labelWidth="100px"
        @submit="onsubmit"
      />
    </vxe-card>

    <vxe-card
      title=""
      class="w-full mt-[16px] h-[36vh]"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{
          t("tea_infuser.dashboard.trend_title")
        }}</span>
        <el-link type="primary" :underline="false" @click="exportExcel('qs')"
          >{{ t("table.export") }}
        </el-link>
      </h3>
      <div
        ref="lineChartRef"
        v-loading="chartLoading"
        style="width: 99%; height: calc(36vh - 56px)"
      />
    </vxe-card>

    <!--    <vxe-card title="" class="w-full mt-[16px]" :border="false">-->
    <!--      <div ref="barChartRef" style="width: 100%; height: 25vh" />-->
    <!--    </vxe-card>-->

    <vxe-card
      title=""
      class="mt-[16px] h-[68vh] w-full pb-4"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{
          t("tea_infuser.dashboard.data_summary_title")
        }}</span>
        <el-link type="primary" :underline="false" @click="exportExcel('make')"
          >{{ t("table.export") }}
        </el-link>
      </h3>
      <div v-loading="makeLoading" class="h-[calc(100%_-_45px)]">
        <AuTable
          v-if="active === 3"
          ref="tableMakeRef"
          v-bind="gridOptionMake"
        />
      </div>
    </vxe-card>

    <vxe-card
      title=""
      class="mt-[16px] h-[68vh] w-full pb-4"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{
          t("tea_infuser.dashboard.material_title")
        }}</span>
        <el-link
          type="primary"
          :underline="false"
          @click="exportExcel('material')"
          >{{ t("table.export") }}
        </el-link>
      </h3>
      <div v-loading="detailLoading" class="h-[calc(100%_-_45px)]">
        <AuTable
          v-if="active === 3"
          ref="tableMtRef"
          v-bind="gridOptionDetail"
        />
      </div>
    </vxe-card>

    <vxe-card
      v-show="radio != '1'"
      class="mt-[16px] w-full"
      :padding="false"
      :border="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{
          t("tea_infuser.dashboard.alarm_title")
        }}</span>
        <el-link type="primary" :underline="false" @click="exportExcel('alarm')"
          >{{ t("table.export") }}
        </el-link>
      </h3>
      <div class="h-[48vh]">
        <AuTable v-if="active === 3" ref="tableAlarmRef" v-bind="gridOption">
          <template #status_default>
            <el-tag type="danger"
              >{{ t("tea_infuser.dashboard.status_abnormal") }}
            </el-tag>
          </template>
        </AuTable>
      </div>
    </vxe-card>
  </div>
</template>

<style lang="scss">
.device-popper {
  width: 200px;

  .el-select-dropdown {
    width: 100% !important;

    .el-select-dropdown__list.el-vl__window {
      width: 100% !important;
    }
  }
}
</style>
